package com.laicunba.util;

public class UserAgentUtil {

	/**
	 * 
	 * @param userAgent
	 * @return ["iphone","version","device"]
	 */
	public static String[] parse(String userAgent) {
		try {
			if (StringUtil.isEmpty(userAgent) || !userAgent.contains("(") || !userAgent.contains(")")) {
				return new String[] { "", "", "" };
			}
			userAgent = userAgent.substring(userAgent.indexOf("(") + 1, userAgent.indexOf(")"));

			if (userAgent.toLowerCase().contains("iphone")) {
				String [] rs =  new String[] { "iphone", StringUtil.findOne(userAgent, "[0-9_]{3,20}"), "iphone" };
				if(StringUtil.isNotEmpty(rs[1])){
					rs[1]=rs[1].replace('_', '.');
				}
				return rs;
			} else if (userAgent.toLowerCase().contains("android")) {
				String tmp[] = userAgent.split(";");
				String device = tmp[tmp.length - 1];
				if(!device.toLowerCase().contains("build")){
					for(String t:tmp){
						if(t.toLowerCase().contains("build")){
							device = t;
							break;
						}
					}
				}
				device = device.substring(0, device.lastIndexOf(" ")).trim();
				return new String[] { "android", StringUtil.findOne(userAgent, "[0-9\\.]{3,20}"), device };
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new String[] { "", "", "" };
	}

}
